package com.cysyz.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class Mail {
		private Message msg;
		private Set<String> attachFilePaths = new HashSet<String>();
		private String htmlConent;
		public Mail(Message msg, String htmlConent) {
			this.msg = msg;
			this.htmlConent = htmlConent;
		}
		public void addAttacthFile(String fileFullPath) {
			attachFilePaths.add(fileFullPath);
		}
		
		public void send() {
			try {
				populateMail();
				Transport.send(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
		private void populateMail() throws MessagingException, UnsupportedEncodingException {
			if (attachFilePaths != null) {
				MimeMultipart multipart = new MimeMultipart("mixed");
				msg.setContent(multipart);
				MimeBodyPart content = new MimeBodyPart();
				content.setContent(htmlConent, "text/html;charset=UTF-8");
				multipart.addBodyPart(content);
				for (String attachFilePath : attachFilePaths) {
					MimeBodyPart attachFile = new MimeBodyPart();
					FileDataSource ds = new FileDataSource(attachFilePath);
					attachFile.setDataHandler(new DataHandler(ds));
					attachFile.setFileName(MimeUtility.encodeText(ds.getName(), "UTF-8", "B"));
					multipart.addBodyPart(attachFile);
				}
				
			} else {
				msg.setContent(htmlConent, "text/html;charset=UTF-8");
			}
		}
	}